#Tai-Hsien Ou Yang
#July 10
library('mecdf')


#/nfs/apps/R/2.9.0/bin/Rscript

setwd("/ifs/scratch/c2b2/ip_lab/to2232/lk")

FILE_INPUT_PED1="parchild.lst"
FILE_INPUT_PED2="parchild.lst"

FILE_INPUT_NAME ="PopIndex.txt"
FILE_INPUT_PROB ="Lengths.txt"
FILE_OUTPUT_LK ="lk.cpc.txt"
FILE_OUTPUT_X ="cpc.txt"

pair1<-scan(FILE_INPUT_PED1 , list(id1="",id2="")) #Parent-Child, directed network: search for the overlap of 2nd column of both lists.
pair2<-scan(FILE_INPUT_PED2 , list(id1="",id2="")) #Parent-Child
idx<-scan(FILE_INPUT_NAME , list(id=""))

pair.prob1<-read.table(FILE_INPUT_PROB, list(p=""))
pair.prob2<-read.table(FILE_INPUT_PROB, list(p=""))


trio.list=matrix(0,length(pair$id1),5) #col: common.id, id1, id2, pair.prob1, pair.prob2 

dim(trio.list) <- c(nx, ny)
for ( i in 1:length(pair$id1))  
{
	j=which(pair1$id1[i] %in% pair2$id1) #Position of common id in list2
	trio.list(i,1)=pair1$id2[i]
	trio.list(i,2)=pair1$id2[i]
	trio.list(i,3)=pair2$id1[i]
	trio.list(i,4)=pair.prob1$p[j]
	trio.list(i,5)=pair.prob2$p[j]
}

write.table(trio.list, file = FILE_OUTPUT_X,col.names=F,row.names=F)

#Generate models
pcdf<-mecdf (trio.list[:,4:5], continuous=FALSE, validate=TRUE,  project=FALSE, expandf=0.1)


#Use the model to predict the likelihood
lkmatrix<-list(id1=0,id2=0,id3=0,length=0)
for(i in 1:length(idx$id)) #
{
		lk<-pcdf(matrix( c(trio.list[i,4],trio.list[i,5]), ncol=2))
		lkmatrix<-rbind(lkmatrix,list(id1=i,id2=j,id3=k,length=lk))
}

write.table(lkmatrix, file = FILE_OUTPUT_LK,col.names=F,row.names=F)

